package com.loiot.baqi.service.job;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.loiot.baqi.constant.ApplicationConst;
import com.loiot.baqi.dao.ZpCompanyJobInfoDao;
import com.loiot.baqi.pojo.ZpCompanyJobInfo;
import com.loiot.baqi.status.CompanyJobSourceType;
import com.loiot.baqi.status.HeartbeatJobType;
import com.loiot.baqi.status.PauseStartType;
import com.loiot.baqi.utils.HdHttpUtils;
import com.loiot.baqi.utils.HtmlUnitUtil;
import com.loiot.baqi.utils.JsonToObject;
import com.loiot.baqi.utils.JsonUtils;
import com.loiot.baqi.utils.MD5Util;
import com.loiot.baqi.vo.hd.Root;
import com.loiot.commons.utils.DateUtil;

@Service("checkHdCompanyJobStopStatus")
@Scope("prototype")
public class CheckHdCompanyJobStopStatus extends JobTaskDefine {

	@Resource
	private ZpCompanyJobInfoDao zpCompanyJobInfoDao;
	
	HdHttpUtils httpUtils = new HdHttpUtils();

	
	@Override
	public void doTask() {
		httpUtils.setCookies("");
		String userName =ApplicationConst.HD_HR_LOGIN_NAME;
		String pwd = ApplicationConst.HD_HR_LOGIN_PWD;
		try {
			 int count=0;
			 HashMap<String, Object> pMap= new HashMap<String,Object>();
			 pMap.put("source", CompanyJobSourceType.HD.getCode());
			 pMap.put("isDelete", PauseStartType.START.getCode());
		     //pMap.put("startTime",DateUtil.addDays(new Date(), -7));
			 List<ZpCompanyJobInfo> companyJobList = zpCompanyJobInfoDao.queryZpCompanyJobInfoList(pMap);

			 if(companyJobList!=null && companyJobList.size()>0){
				 String loginResult =httpUtils.login(userName, pwd, "");
				 System.out.println("需要检查"+companyJobList.size()+"个职位");

				 System.out.println("登陆成功，返回的个人信息="+loginResult);
				 Map<String, Object> parseJSON2Map = JsonToObject.parseJSON2Map(loginResult);
				 boolean flag =  (Boolean) parseJSON2Map.get("success");
				 if(flag){
					 for(ZpCompanyJobInfo jobInfo:companyJobList){
						 
							//jobInfo.setHdCode(32471l);
							 String url5="http://hd.hunteron.com/api/v1/position/detail?_t="+System.currentTimeMillis()+"&positionId="+jobInfo.getHdCode();
					 		 String jobRootJson = this.httpUtils.httpGet(url5,2000,4000); //获取职位信息
					 		 Root root = JsonUtils.fromJsonToObject(jobRootJson.trim(), Root.class);		
							 //说明该职位已暂停  （暂停站内职位）
					 		String TerminatedReason=root.getData().getPosition().getTerminatedReason();
					 		 if(TerminatedReason!=null && TerminatedReason.length()>0){
					 			ZpCompanyJobInfo newJob = new ZpCompanyJobInfo();
					 			newJob.setJobId(jobInfo.getJobId()); 
					 			newJob.setIsDelete((int)PauseStartType.PAUSE.getCode());
					 			zpCompanyJobInfoDao.updateZpCompanyJobInfo(newJob);
					 			count++;
					 		 }
							 
						 }
						 System.out.println("暂停了共="+count+"个");
				 }
			  }
			 
		} catch (Exception e) {
			// TODO Auto-generated catch block
			super.exceptionContent=e.getMessage();
		}finally{
			//添加心跳
			super.jobType=(int)HeartbeatJobType.CHECK_HD_COMPANY_JOB_STOP_STATUS.getCode();
			super.addHeartbeat();
		}
		
	}
	
	
	/**
	 * 模拟登陆 猎上
	 * @param userName
	 * @param pwd
	 * @param yzm
	 * @throws FailingHttpStatusCodeException
	 * @throws IOException
	 */
	public  void login(String userName, String pwd, String yzm) throws FailingHttpStatusCodeException, IOException{
		
		String url0 = "http://hd.hunteron.com/#/index?redirect=http%253A%252F%252Fhd.hunteron.com%252F%2523%252Fpositions%252Fmatch";
		HtmlUnitUtil.webClientGet(url0,1000,2000); //获取cookie
		
		String url1 = "http://hd.hunteron.com/api/ucenter/link?_t=1453105469239&date=1453105469218";
		String response = HtmlUnitUtil.webClientGet(url1,1000,2000); //获取cookie的同时获取授权码
		Map<String, Object> jsonMap = JsonToObject.parseJSON2Map(response);
		Map<String, Object> dataMap = (Map<String, Object>) jsonMap.get("data");
		String realm = (String) dataMap.get("realm");
		String nonce = (String) dataMap.get("nonce");
		String a = MD5(pwd);
		String b = MD5(a + "5OGP56W65A6D6LSD") + "x";
		String o = jsFunction(a, userName,realm, nonce);
		String s = jsFunction(b, userName,realm, nonce);
		
		String url3 = "http://hd.hunteron.com/api/ucenter/login?_t="+System.currentTimeMillis();
		Map<String, String > params = new HashMap<String, String>();
		params.put("loginName",userName);
		params.put("authorizeCode",o);
		params.put("twoAuthorizeCode",s);
		params.put("noRemind","true");
	//	params.put("imageVeriCode","yrez");
		String webClientPost = HtmlUnitUtil.webClientPost(url3, params);
		//System.out.println(webClientPost);
	}
	private  String jsFunction(String a0, String userName,  String realm, String nonce) {
		String a1 = MD5(userName + ":" + realm + ":" + a0);
		String r = MD5("POST:/ucenter/login");
		String o = MD5(a1 + ":" + nonce + ":" + r);
		return o;
	}
	
	
	private  String MD5(String string) {
		String md5yzm = MD5Util.encode(string);
		//String md5yzm = MD5.digest(string);
//		md5yzm  = md5yzm.substring("MD5:".length());
		//System.out.println("md5 :"+md5yzm);
		return md5yzm;
		
	}

}
